from django.core.exceptions import ValidationError

from django.shortcuts import render, redirect
from django import forms

from app01 import models
from app01.utils.pagination import Pagination

from app01.utils.encrypt import md5


def admin_list(request):

    """amdin列表"""


    data_dict = {}

    search_data = request.GET.get('query', "")  # 不加后面的 "", 首次访问浏览器,搜索框中不会显示前端页面中的 placeholder="Search for..." 属性
    if search_data:
        data_dict["username__contains"] = search_data

    admin_data = models.Admin.objects.filter(**data_dict).order_by("id")


#################分页代码#########


    page_object = Pagination(request, admin_data, page_size=10, page_param="page")
    page_queryset = page_object.page_queryset

    # 调用对象的html方法,生成页码
    page_object.html()

    page_string = page_object.page_string
    head_page = page_object.head_page
    end_page = page_object.end_page

    context = {
        "admin_data": page_queryset,  # 分页的数据
        "search_data": search_data,  # 搜索的内容
        "page_string": page_string,  # 页码
        "head_page": head_page,  # 首页
        "end_page": end_page,  # 尾页
    }

    return render(request, "admin_list.html", context)


def admin_del(request):
    """删除"""
    if request.method == 'GET':
        nid=request.GET.get("nid")
        models.PrettyNum.objects.filter(id=nid).delete()
        return redirect("/admin/list/")





class AdminModelForm(forms.ModelForm):


    confirmpassword = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True)
    )


    class Meta:
        model = models.Admin
        fields = ['username','password','confirmpassword']
        widgets = {
            "password": forms.PasswordInput(render_value=True)

        }



    def clean_password(self):
        password = self.cleaned_data.get("password")

        return md5(password)
    def clean_confirmpassword(self):
        password = self.cleaned_data.get("password")
        confirmpassword = md5(self.cleaned_data.get("confirmpassword"))
        if password != confirmpassword:
            raise ValidationError("两次密码不一致")
        return confirmpassword


    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name,field in self.fields.items():
            field.widget.attrs={"class" :"form-control"}



from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=models.PrettyNum)
def update_id(sender, instance, **kwargs):
    if instance.id is None:
        last_id = models.Admin.objects.all().order_by('-id').first().id
        instance.id = last_id + 1 if last_id else 1
def admin_add(request):
    """添加"""

    if request.method == "GET":
        form=AdminModelForm()
        return render(request, "admin_add.html",{"form":form})

    #数据效验
    form=AdminModelForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect("/admin/list")

    return render(request, "admin_add.html", {"form": form})


class AdminEditModelForm(forms.ModelForm):
    class Meta:
        model = models.Admin
        # fields = "__all__"    表示取表中所有的字段
        fields = ['username','password']
        # exclude = ['level']   表示取除了表中的某个字段的所有字段

    # 循环找到所有的插件,加入css样式,添加 "class": "form-control"
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for name, field in self.fields.items():
            print(name, field)
            field.widget.attrs = {"class": "form-control"}




def admin_edit(request,id):
    """用户编辑"""
    row_object=models.Admin.objects.filter(id=id).first()
    if not row_object:
        return redirect("/admin/list/")
    if request.method == "GET":


        form = AdminModelForm(instance=row_object)



        return render(request, "admin_edit.html",{"id":id,"form":form})



    form=AdminModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/admin/list/")
    else:
        print(form.errors)
        return render("admin_edit.html", {"form":form})


class AdminResetModelForm(forms.ModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True),
    )

    class Meta:
        model = models.Admin
        fields = ["password", "confirm_password"]
        widgets = {
            "password": forms.PasswordInput(render_value=True)
        }

    # clean_字段名
    def clean_password(self):
        pwd = self.cleaned_data.get("password")

        # 校验当前数据库中的密码与用户输入的新密码是否一致
        exists = models.Admin.objects.filter(id=self.instance.pk, password=md5(pwd))
        if exists:
            raise ValidationError("密码不能与当前密码一致!")

        # return什么.password字段保存什么
        return md5(pwd)

    # 钩子函数
    def clean_confirm_password(self):
        pwd = self.cleaned_data.get("password")
        confirm = self.cleaned_data.get("confirm_password")
        if md5(confirm) != pwd:
            raise ValidationError("密码不一致!")

        # return返回什么,字段 confirm_password 保存至数据库的值就是什么
        return md5(confirm)


def admin_reset(request, nid):
    """重置管理员密码"""

    # 判断 nid 是否存在
    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        return ValidationError("数据不存在")

    title = "重置密码 - {}".format(row_object.username)

    if request.method == "GET":
        form = AdminResetModelForm(instance=row_object)

        return render(request, "admin_edit.html", {"title": title, "form": form})

    form = AdminResetModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/admin/list/")

    return render(request, "admin_edit.html", {"title": title, "form": form})